<?php
class hschool_organization{
	public $info_array = array();
	public $page_array = array();
	public $tree_array = array();
	public static $all_organization_array = array();

	static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}

	/*
	*	取出一个课程信息
	*/
	public function get_one($id='') {
		$info = array();
		if($id){
			$sql = "SELECT * FROM ".DB::table('school')." WHERE d_id='".$id."' LIMIT 1";
			$info = DB::fetch_first($sql);
            $sql = "SELECT d_name,d_parent_id,d_order FROM ".DB::table('dictionary')." WHERE d_id='".$id."' LIMIT 1";
			$d_info = DB::fetch_first($sql);
            $info['d_name'] = $d_info['d_name'];
            $info['d_order'] = $d_info['d_order'];
            $info['d_parent_id'] = $d_info['d_parent_id'];
            $info['d_parent_name'] = ext::d_name($d_info['d_parent_id']);
		}
		return $info;
	}

	/*
	*	创建课程
	*/
	public function add() {
		global $_G;
        //DEBUG 学段数据
        $system_school_type_array = array();
        if($_G['setting']['system_school_type']){
            $tmp1 = explode(',',$_G['setting']['system_school_type']);
            foreach($tmp1 AS $key => $value){
                $tmp2 = explode('|',$value);
                $system_school_type_array[$tmp2[0]] = $tmp2[1];
            }
        }
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
        $sql = "SELECT d_name,d_level FROM ".DB::table('dictionary')." WHERE d_id='".$_G['member']['dept_id']."' LIMIT 1";
        $user_info = DB::fetch_first($sql);
		if(!empty($is_submit)){
			$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
            $d_string = isset($_REQUEST['d_string']) ? $_REQUEST['d_string']:'';
            if($d_string){
                $hschool_dept = load_class('hschool','dept');
                $user_depts_array = $hschool_dept->get_tree_path_id($d_string);
            }
            $data['school_intro'] = isset($_REQUEST['school_intro']) ? $_REQUEST['school_intro']:'';
            $data['school_type'] = isset($_REQUEST['school_type']) ? $_REQUEST['school_type']:'';
            $data['school_img'] = isset($_REQUEST['school_img']) ? $_REQUEST['school_img']:'';
            $data['school_status'] = isset($_REQUEST['school_status']) ? $_REQUEST['school_status']:'';
            $data['area_id1'] = isset($user_depts_array[1]) ? $user_depts_array[1]:0;
            $data['area_id2'] = isset($user_depts_array[2]) ? $user_depts_array[2]:0;
            $data['area_id3'] = isset($user_depts_array[3]) ? $user_depts_array[3]:0;
            //DEBUG 兼容字段数数据
            $d_name = isset($_REQUEST['d_name']) ? $_REQUEST['d_name']:'';
            $d_order = isset($_REQUEST['d_order']) ? $_REQUEST['d_order']:'';
            //DEBUG 父级层级级别
            $sql = "SELECT d_level FROM ".DB::table('dictionary')." WHERE d_id='".$d_string."' LIMIT 1";
            $school_parent_d_level = DB::result_first($sql);
            $data_dictionary = array(
                "d_name"=>$d_name,
                "d_parent_id"=>$d_string,
                "d_order"=>$d_order,
                "d_type"=>2,
                "d_level"=>$school_parent_d_level+1,
                "d_root_id"=>100
             );
             //DEBUG 接收网校管理员微客号 开始
            $school_master_user_ids = isset($_REQUEST['school_master_user_ids']) ? $_REQUEST['school_master_user_ids']:'';
            $school_master_user_ids_array = array();
            if($school_master_user_ids){
                $school_master_user_ids_array = explode(',',$school_master_user_ids);
            }
            //DEBUG 接收网校管理员微客号 结束
			if($id){
                //DEBUG 编辑 更新网校管理员 开始
                //DEBUG 先删除现有网校管理员,再添加网校管理员 减少反复判断是否存在与是否非管理员更新过程
                $sql = "DELETE FROM ".DB::table('org_user')." WHERE ou_d_id='".$id."' AND is_master=1 || ou_user_id IN (".dimplode($school_master_user_ids_array).") LIMIT 100";
                @DB::query($sql);
                if($school_master_user_ids_array){
                    foreach($school_master_user_ids_array AS $key => $value){
                        $user_role_id = @DB::result_first("SELECT user_role_id FROM ".DB::table('users')." WHERE user_id='".$value."' LIMIT 1");
                        if($user_role_id){
                           $insert_org_user_data = array(
                               'ou_d_id'=>$id,
                                'ou_user_id'=>$value,
                                'user_role_id'=> $user_role_id,
                                'is_master'=>1
                            );
                        }
                        //TODO 管理员插入成功计数 是否完整插入
                        @DB::insert('org_user',$insert_org_user_data);
                    }
                }
                //DEBUG 编辑 更新网校管理员 结束
                $data_dictionary['modify_time'] = TIMESTAMP;
                $effect1 = DB::update('dictionary',$data_dictionary,array('d_id'=>$id));
                $data['modify_dateline'] = TIMESTAMP;
				$effect2 = DB::update('school',$data,array('d_id'=>$id));
			}else{
                //DEBUG 新建 插入网校管理员记录
                $data_dictionary['create_time'] = TIMESTAMP;
                $effect1 = DB::insert('dictionary',$data_dictionary,1);
                $data['create_user_id']=$_G['user_id'];
                $data['create_dateline'] = TIMESTAMP;
                $data['d_id'] = $effect1;
				$effect2 = DB::insert('school',$data,1);
                if($effect2){
                    //DEBUG 插入网校管理员记录 开始
                    if($school_master_user_ids_array){
                        foreach($school_master_user_ids_array AS $key => $value){
                            $user_role_id = @DB::result_first("SELECT user_role_id FROM ".DB::table('users')." WHERE user_id='".$value."' LIMIT 1");
                            if($user_role_id){
                                $insert_org_user_data = array(
                                    'ou_d_id'=>$effect1,
                                    'ou_user_id'=>$value,
                                    'user_role_id'=> $user_role_id,
                                    'is_master'=>1
                                );
                            }
                            //TODO 管理员插入成功计数 是否完整插入
                            @DB::insert('org_user',$insert_org_user_data);
                        }   
                    }
                    //DEBUG 插入网校管理员记录 结束
                }
			}
			if($effect1 && $effect2){
				self::return_json(false,'操作成功');
			}else{
				self::return_json();
			}
		}else{
			include template('admin/hschool/organization_add');	
		}
	}

	/*
	*	编辑课程
	*/
	public function edit() {
		global $_G;
        //DEBUG 学段数据
        $system_school_type_array = array();
        if($_G['setting']['system_school_type']){
            $tmp1 = explode(',',$_G['setting']['system_school_type']);
            foreach($tmp1 AS $key => $value){
                $tmp2 = explode('|',$value);
                $system_school_type_array[$tmp2[0]] = $tmp2[1];
            }
        }
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){

		}else{
			$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
			$info = $this->get_one($id);
            $sql = "SELECT d_name,d_level FROM ".DB::table('dictionary')." WHERE d_id='".$_G['member']['dept_id']."' LIMIT 1";
            $user_info = DB::fetch_first($sql);
            //DEBUG 取出网校管理员 开始
            if($id){
                $sql = "SELECT ou_user_id FROM ".DB::table('org_user')." WHERE ou_d_id='".$id."' AND is_master=1 LIMIT 100";
                $ouresult = DB::fetch_all($sql);
                $school_master_user_ids_array = array();
                foreach($ouresult AS $oukey => $ouvalue){
                    $school_master_user_ids_array[] = $ouvalue['ou_user_id'];
                }
                $info['school_master_user_ids'] = implode(',',$school_master_user_ids_array);
            }
            //DEBUG 取出网校管理员 结束
			include template('admin/hschool/organization_add');
		}
	}

	/*
	*	删除课时
	*/
	public function del() {
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){
			$d_ids_array = array();
			$d_ids_array = isset($_REQUEST['d_ids']) ? $_REQUEST['d_ids']:array();
			if($d_ids_array){
				$update = array(
					'isdelete'=> 1
				);
				$where = ' d_id IN ('.dimplode($d_ids_array).') ';
				$effects1 = DB::update('school',$update,$where);
                $effects2 = DB::update('dictionary',$update,$where);
			}
			//DEBUG 接收用户信息 end
			$this->return_json(false,'操作成功');
			echo json_encode($return_array);
		}
	}

	/*
	*	当前动作的首页
	*/
	public function index() {
		global $_G;
		$page_array = array();
		$sqlcount = $sql = $wheresql = $keyword = $pageNum = $numPerPage = '';
		$pageNum = isset($_REQUEST['pageNum']) ? $_REQUEST['pageNum'] : 1;
		$numPerPage = isset($_REQUEST['numPerPage']) ? $_REQUEST['numPerPage'] : 10;
		$pagestart = ($pageNum - 1) * $numPerPage;
		//DEBUG 分层级管理 取出子单位机构 如果是单位管理员则带上本单位编号
		$hschool_dept = load_class('hschool','dept');
		if($hschool_dept){
			$d_id_array=array();
			$d_id_array = $hschool_dept->get_sub_tree($_G['dept_id'],2);
			if(!empty($d_id_array)){
				$d_id_array=array_keys($hschool_dept->tree2array($d_id_array));
			}
			if($_G['member']['is_dept_master']){
				//$d_id_array[] = $_G['dept_id'];
                //DEBUG 是否地区用户
                $sql = "SELECT d_id FROM ".DB::table('dictionary')." WHERE d_id='".$_G['dept_id']."' AND d_type=2 LIMIT 1";
                $d_result=DB::fetch_first($sql);
                if($d_result){
                   $d_id_array[] = $d_result['d_id']; 
                }
                //DEBUG 取出用户管理机构 结束
                $sql = "SELECT * FROM ".DB::table('dictionary')." WHERE d_id='".$_G['dept_id']."' LIMIT 1";
                $d_result=DB::fetch_first($sql);
			}
            //DEBUG 取出用户管理机构 开始
            $sql = "SELECT ou_d_id FROM ".DB::table('org_user')." WHERE ou_user_id='".$_G['user_id']."' AND is_master=1";
            $d_org_result=DB::fetch_all($sql);
            if($d_org_result){
                foreach($d_org_result AS $key =>$value){
                    $d_id_array[] = $value['ou_d_id'];
                }
            }
		}
        if($d_id_array){
            $wheresql .= " AND s.d_id IN (".dimplode($d_id_array).") ";
        }else{
            $wheresql .= " AND s.create_user_id = '".$_G['user_id']."' ";
        }
		$sqlcount = "SELECT count(*) from ".DB::table('school')." AS s WHERE s.isdelete=0 ".$wheresql;
		$pagetotal = DB::result_first($sqlcount);
		$sql = "SELECT s.* from ".DB::table('school')." AS s WHERE s.isdelete=0 ".$wheresql." ORDER BY s.school_key DESC LIMIT ".$pagestart.",".$numPerPage;
		$page_array = DB::fetch_all($sql);
        //DEBUG 学段数据
        $system_school_type_array = array();
        if($_G['setting']['system_school_type']){
            $tmp1 = explode(',',$_G['setting']['system_school_type']);
            foreach($tmp1 AS $key => $value){
                $tmp2 = explode('|',$value);
                $system_school_type_array[$tmp2[0]] = $tmp2[1];
            }
        }
		foreach($page_array AS $key => $value){
			$page_array[$key]['d_name'] = ext::d_name($value['d_id']);
			$page_array[$key]['school_type_name'] = $system_school_type_array[$value['school_type']];
			$page_array[$key]['area_name'] = ext::d_name($value['area_id1']).ext::d_name($value['area_id2']).ext::d_name($value['area_id3']);
		}
		//总页数
		$realpages = @ceil($pagetotal / $numPerPage);
		if($realpages <= 0){
			$realpages=1;
		}
		//前一页
		$page_pre = max(1, intval(($pageNum-1)));
		//后一页
		$page_next = min(intval(($pageNum+1)), $realpages);
		include template('admin/hschool/organization');
	}
    
	/*
	* ajax 返回信息
	*/
	public function return_json($error='true',$message="操作失败") {
		$return_array = array(
			"error" => $error,
			"message" => $message
		);
		echo json_ext($return_array);
		die;
	}
}
?>